/**
 * StartFileServiceClient.java
 */
package fss;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
import java.util.Scanner;

import fss.client.FssClient;
import fss.remote.RemoteService;
import fss.remote.util.RemoteFileService;
import fss.util.rmi.RmiId;
import fss.util.rmi.RmiUtils;

/**
 * This is a command line utility to start and stop a Remote Client.
 * 
 * @author thinh
 *
 */
public class StartFileServiceClient {
    /**
     * Application entry.
     * @param args not used.
     * @throws RemoteException 
     */
    public static void main(String[] args) throws RemoteException {
        Scanner stdin = new Scanner(System.in);        
        System.out.println("********************************************************************");      
        System.out.println("File Service Client");
        System.out.println("********************************************************************");
        System.out.println();
        
        String host, name;
        int port;
        RmiId id = null;
        RmiId serviceId = null;
        
        System.out.println("- Remote Service Input -");
        System.out.print("Enter host: ");
        host = stdin.nextLine();
        System.out.print("Enter port: ");
        port = Integer.parseInt(stdin.nextLine());
        System.out.print("Enter service name: ");
        name = stdin.nextLine();        
        System.out.println();
        serviceId = new RmiId(host, name, port);
        RemoteFileService service = (RemoteFileService)RmiUtils.getRemoteObject(serviceId);
        if(service == null) {
            throw new RemoteException("Attempt to obtain a Remote Service failed at id " + serviceId);
        }
        System.out.println();
        
        System.out.println("- File Service Client Input -");
        System.out.print("Enter host: ");
        host = stdin.nextLine();
        System.out.print("Enter port: ");
        port = Integer.parseInt(stdin.nextLine());
        System.out.print("Enter service name: ");
        name = stdin.nextLine();        
        System.out.println();
        id = new RmiId(host, name, port);
        
        FssClient client = new FssClient(id);
        Registry rmi = RmiUtils.exportFssClient(client);
        service.register(client);
        
        System.out.println("******************************************************");      
        System.out.println("Hit enter at any time to remove/stop the Client...");
        System.out.println("******************************************************");
        System.out.println();
        stdin.nextLine();
        
        try {
            rmi.unbind(id.getName());
        } catch (NotBoundException e) {
            // ignore
        }
        System.out.println("Client ended.");
        System.exit(0);
    }

}
